package com.lagou.homework.filter;

import com.lagou.homework.service.UserService;
import io.netty.handler.codec.http.cookie.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.Cookies;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/*
    验证 是否有token 若没有 不允许调用服务
 */
@Component
public class ProtectTokenGatewayFilter implements GatewayFilter, Ordered {

    //@Autowired
    //UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> list = cookies.get("token");
        if (list!=null){
            HttpCookie httpCookie = list.get(0);
            String token = httpCookie.getValue();
            System.out.println(token);
            // 能根据token 获取 email
            //String email = userService.info(token);
            if (!"".equals(token)|| token == null){
                return chain.filter(exchange);
            }else {
                // 设置编码
                response.getHeaders().set("Content-Type","application/json;charset=UTF-8");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                String data = "错误码：401，错误信息：您没有权限，请求已被拒绝";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }else {
            response.getHeaders().set("Content-Type","application/json;charset=UTF-8");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "错误码：401，错误信息：您没有权限，请求已被拒绝";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
